package jp.ac.u_tokyo.dch.model.xml.tree;

import java.util.ArrayList;
import java.util.List;

public class TreeEntry extends Entry {

	private List<Entry> childs = new ArrayList<Entry>();


	public TreeEntry(String name) {

		setName(name);
	}

	public void addData(int level, List<TreeData> dataList) {

		String dataName = dataList.get(level).getLabel();
		String value = dataList.get(level).getValue();

		if (!isExists(dataName) && level < dataList.size() - 1) {

			childs.add(new TreeEntry(dataName));

		} else if (!isExists(dataName)){

			childs.add(new LeafEntry(dataName, value));
		}
		if (level < dataList.size() - 1) {

			for (Entry child : childs) {

				if (child.getName().equals(dataName)) {
					child.addData(level + 1, dataList);
				}
			}
		}
	}

	public String print() {

		StringBuilder output = new StringBuilder();

		output.append("<group name=\"");
		output.append(getName());
		output.append("\">");


		for (Entry child : childs) {

			output.append(child.print());

		}
		output.append("</group>");

		return output.toString();
	}

	private boolean isExists(String dataName) {

		for (Entry child : childs) {

			if (child.getName().equals(dataName)) {
				return true;
			}
		}

		return false;

	}
}
